// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.android.apps.moderator;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.ListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * View for a Series.
 */
public class SeriesActivity extends RefreshableActivity {

  private static final String TAG = SeriesActivity.class.getName();

  private ListSynchronizer listSynchronizer;

  private static final int MAX_RECENTS = 2;
  
  private void addToMostRecentSeriesList(JSONObject series) {
    final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);

    JSONArray recents;

    // Recover existing recently loaded series from the preference store, or create a new blank one.
    if (preferences.contains(PREFERENCE_KEY_RECENT_SERIES)) {
      try {
        recents = new JSONArray(preferences.getString(PREFERENCE_KEY_RECENT_SERIES, null));
      } catch (JSONException e) {
        Log.e(TAG, "An error occurred", e);
        recents = new JSONArray();
      }
    } else {
      recents = new JSONArray();
    }

    try {
      
      boolean exists = false;
      int seriesId = series.getJSONObject("data").getJSONObject("id").getInt("seriesId");
      
      // Make sure this series is not already in the list
      int length = recents.length();
      for (int idx = 0; idx != length; idx++) {
        int thisId =
            recents.getJSONObject(idx).getJSONObject("data").getJSONObject("id").getInt("seriesId");
        if (seriesId == thisId) {
          exists = true;
          break;
        }
      }
      
      if (!exists) { 
        if (length > MAX_RECENTS) {
          for (int idx = 0; idx != length - 1; idx++) {
            recents.put(idx, recents.getJSONObject(idx + 1));
          }
          length--;
        }
        recents.put(length, series);
        Editor edit = preferences.edit();
        edit.putString(PREFERENCE_KEY_RECENT_SERIES, recents.toString());
        edit.commit();
      }
    } catch (JSONException e) {
      throw new RuntimeException(e);
    }
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {

    setContentView(R.layout.series);
    final ListView listView = (ListView) findViewById(R.id.Content);
    List<Integer> list = new ArrayList<Integer>();
    list.add(R.layout.series_entry);
    list.add(R.layout.series_entry_compact);
    list.add(R.layout.topic_entry);
    listSynchronizer = new ListSynchronizer(this, listView, list);
    refresh();
    super.onCreate(savedInstanceState);
  }

  @Override
  void refresh() {
    showProgress();

    new Thread(new Runnable() {

      public void run() {
        try {
          final int seriesId = getIntent().getIntExtra("seriesId", -1);

          List<ListEntry> entries = new ArrayList<ListEntry>();

          JSONObject seriesJson = 
              getJsonData(ModeratorActivity.API_URL_BASE + "series/" + seriesId);
          addToMostRecentSeriesList(seriesJson);
          entries.add(new SeriesListEntry(getJsonData(API_URL_BASE + "series/" + seriesId), false));

          JSONObject topics = getJsonData(API_URL_BASE + "series/" + seriesId + "/topics");

          JSONArray array = topics.getJSONObject("data").getJSONArray("items");
          if (array.length() > 0) {
            setHasContent(true);
            for (int idx = 0; idx != array.length(); idx++) {
              JSONObject topic = (JSONObject) array.get(idx);
              entries.add(new TopicListEntry(topic, false));
            }
          }

          listSynchronizer.setEntries(entries);
          hideProgress();
        } catch (final AuthenticationProblem e) {
          startActivity(new Intent(SeriesActivity.this, LoginActivity.class));
        } catch (AccessException e) {
          generalError(e, e.getMessageId());
        } catch (JSONException e) {
          generalError(e, R.string.a_problem_occurred);
        }

      }

    }).start();
  }
}
